﻿using System;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Runtime.InteropServices;

public class FontManager
{
    public FontManager()
    {

    }

    public Font ScaleTextToRectangle(Graphics g, String Text, Rectangle R, Font font)
    {
        float fontSize = 1f;
        FontFamily FontToUse = font.FontFamily;

        Font tmpFont = new Font(FontToUse, fontSize);
        SizeF CurrentTextSize = g.MeasureString(Text, tmpFont);

        while (CurrentTextSize.Width < R.Width && CurrentTextSize.Height < R.Height)
        {
            fontSize += 0.5f;
            tmpFont.Dispose();
            tmpFont = new Font(FontToUse, fontSize);
            CurrentTextSize = g.MeasureString(Text, tmpFont);
        }

        return new Font(FontToUse, fontSize - 0.5f);
    }

    private PrivateFontCollection privateFontCollection = new PrivateFontCollection();

    [DllImport("gdi32.dll")]
    private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pvd, [In] ref uint pcFonts);

    private FontFamily LoadFont(byte[] fontResource)
    {
        int dataLength = fontResource.Length;
        IntPtr fontPtr = Marshal.AllocCoTaskMem(dataLength);
        Marshal.Copy(fontResource, 0, fontPtr, dataLength);

        uint cFonts = 0;
        AddFontMemResourceEx(fontPtr, (uint)fontResource.Length, IntPtr.Zero, ref cFonts);
        privateFontCollection.AddMemoryFont(fontPtr, dataLength);

        return privateFontCollection.Families.Last();
    }
}
